import React, { Component } from 'react'
import {LanguageDao, FLAG_LANGUAGE} from '../../js/expand/dao/LanguageDao'
import {View, Text, TouchableHighlight,Image, StyleSheet} from 'react-native'
import SortableListView from 'react-native-sortable-listview'


class SortCell extends Component {
  render() {
    return (<TouchableHighlight
    underlayColor={'#eee'}
    style={styles.item}
    {...this.props.sortHandlers}
  >
    <View style={styles.row}>
      <Image style={styles.image} source={require('../../assets/img/ic_sort.png')}></Image> 
      <Text>{this.props.data.name}</Text>
    </View>
  </TouchableHighlight>)
  }
}



export default class SortKeyPage extends Component {
  constructor(props) {
    super(props);
    this.dataArray=[];
    this.sortResult = [];
    this.originalCheckedArray = [];
    this.state = {
      checkedArray: []
    }
  }
  componentDidMount() {
    this.languageDao = new LanguageDao(FLAG_LANGUAGE.flag_key)
    this.loadData()
  }

  loadData() {
    this.languageDao.fetch().then(result => {
      this.getCheckedItems(result)
    }).catch(error => {

    })
  }

  getCheckedItems(result) {
    this.dataArray = result;
    let arr = [];
    for(let i=0; i< result.length; i++) {
      if(result[i].checked) {
        arr.push(result[i])
      }
    }
    this.setState({
      checkedArray: arr
    })
    this.originalCheckedArray = [...arr]
    this.props.navigation.setParams({originalCheckedArray: this.originalCheckedArray})
  }

  render() {
    return (
        <SortableListView
          style={{ flex: 1 }}
          data={this.state.checkedArray}
          order={Object.keys(this.state.checkedArray)}
          onRowMoved={e => {
            this.state.checkedArray.splice(e.to, 0, this.state.checkedArray.splice(e.from, 1)[0])
            this.forceUpdate()
            console.log('123')
            this.props.navigation.setParams({checkedArray: this.state.checkedArray})
          }}
          renderRow={row => <SortCell data={row} />}
        />
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  item: {
    padding: 15,
    backgroundColor: '#f8f8f8',
    borderBottomWidth: 1,
    borderColor: '#eee',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  image: {
    tintColor: '#2196f3',
    height: 16,
    width: 16,
    marginRight: 10
  }
})